<template>
  <a
    :class="[
      'el-link',
      type ? `el-link--${type}` : '',
      disabled && 'is-disabled',
      underline && !disabled && 'is-underline',
      clickChangeColor && isActive && 'is-active'
    ]"
    :href="disabled ? null : href"
    v-bind="$attrs"
    @click="handleClick"
  >

    <i :class="icon" v-if="icon"></i>

    <span v-if="$slots.default" class="el-link--inner">
      <slot></slot>
    </span>

    <template v-if="$slots.icon"><slot v-if="$slots.icon" name="icon"></slot></template>
  </a>
</template>

<script>
const links = new Set()
export default {
  name: 'ElLink',
  data(){
    return {
      isActive:false
    }
  },
  watch:{
    clickChangeColor(){
      if(this.clickChangeColor){
        this.doAddToLinks()
      }else{
        this.doRemoveFromLinks()
        this.isActive = false
      }
    }
  },
  props: {
    type: {
      type: String,
      default: 'default'
    },
    underline: {
      type: Boolean,
      default: true
    },
    clickChangeColor:{
      type: Boolean,
      default: false
    },
    disabled: Boolean,
    href: String,
    icon: String
  },
  methods: {
    handleClick(event) {
      if (!this.disabled) {
        if (!this.href) {
          this.$emit('click', event);
          Array.from(links).forEach(link=>link.isActive=false)
          this.$nextTick(()=>{
            this.isActive = true
          })
        }
      }
    },
    doAddToLinks(){
      if(this.clickChangeColor){
        links.add(this)
      }
    },
    doRemoveFromLinks(){
      links.delete(this)
    }
  },
  beforeDestroy() {
    this.doRemoveFromLinks()
  },
  deactivated() {
    this.doRemoveFromLinks()
  },
  activated() {
    this.doAddToLinks()
  },
  created() {
    this.doAddToLinks()
  }
};
</script>
